package com.zmn.oms.admin.controller.work.modify;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.admin.controller.OmsBaseController;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.work.modify.must.ZsAccountDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkQuery;
import com.zmn.oms.model.vo.work.OperatePermissionVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkOperatePermissionBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.financework.ZsNormalAccountWorkBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.financework.ZsNormalFinanceWorkBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 类描述：工单列表主要操作controller
 *
 * @author lujia
 * @date 2018/11/07 16:32
 */
@Controller
@RequestMapping("/work/modify")
public class WorkAccountController extends OmsBaseController {

    @Autowired
    private ZsNormalFinanceWorkBService zsNormalFinanceWorkBService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderWorkListBService orderWorkListBService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ZsNormalAccountWorkBService zsNormalAccountWorkBService;
    @Autowired
    private ZsOrderWorkOperatePermissionBService zsOrderWorkOperatePermissionBService;
    @Resource
    private RedisManager redisManager;

    /**
     * 算账
     */
    @RequestMapping(value = "/account")
    public ModelAndView account(Long orderId, Long workId) throws OmsBaseException {
        ModelAndView mv = new ModelAndView("work/modify/account/account");
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        zsNormalFinanceWorkBService.verifyOrderAmount(orderWork);
        mv.addObject("orderId", String.valueOf(orderId));
        mv.addObject("workId", String.valueOf(workId));
        return mv;
    }

    /**
     * 保存算账页面
     */
    @RequestMapping(value = "/save/account")
    @ResponseBody
    public ResultDTO saveAccount(OmsOperator operator) {
        // 校验是否已进入自动算账流程
        String redisKey = String.format(RedisKeyConsts.AUTO_ACCOUNT_LOCK_KEY, operator.getWorkId());
        if (redisManager.exists(redisKey)) {
            return ResultDTO.fail("订单已进入自动算账流程，请稍后重试");
        }

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(operator.getOrderId(), operator.getWorkId());
        OperatePermissionVO permissionVO = zsOrderWorkOperatePermissionBService.getOperatePermission(orderWork, OrderConsts.ORDER_OP_TYPE_ACCOUNT, com.zmn.consts.GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        if (permissionVO.getCanOperate()) {
            try {
                // 校验
                zsNormalAccountWorkBService.verifyOrderAmount(orderWork);

                zsNormalAccountWorkBService.account(orderWork, operator);
            } catch (OmsBaseException e) {
                logger.error("算账错误", e);
                return ResultDTO.fail(e.getMessage());
            } catch (Exception e) {
                logger.error("算账错误", e);
                return ResultDTO.fail(e.getMessage());
            }
            return ResultDTO.success();

        } else {
            return ResultDTO.fail(permissionVO.getMsg());
        }

    }

    private boolean canBonus(OrderWork orderWork) {
        // 加单奖励，发送队列到ERP（成功的新单，无退款记录的师傅加单）
        boolean canBonus = Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)
                && Objects.equals(orderWork.getResultStatus(), OrderStatusConsts.WORK_RESULT_SUCCESS)
                && NumberUtil.isNullOrZero(orderWork.getRefundTargetWorkId())
                && Objects.equals(orderWork.getRecommenderType(), GlobalConsts.OPERATE_USER_TYPE_MASTER)
                && NumberUtil.isNotNullOrZero(orderWork.getRecommenderId());

        if (!canBonus) {
            logger.info("工程师恶意加单奖励不满足：成功的新单，无退款记录的师傅加单");
            return false;
        }

        // B1的订单下单用户手机号和下单对应的前台产品和A1订单的对应前台产品一模一样
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderWork.getOrderId());

        String receiveTimeSpan = DateUtil.getDateStartString(DateUtil.toString(DateUtil.addDays(orderWork.getReceiveTime(), -3))) + "," + DateUtil.toString(orderWork.getReceiveTime(), DateUtil.FORMAT_DEFAULT);

        OrderWorkQuery query = new OrderWorkQuery();
        query.setPermit(GlobalConsts.NO);
        query.setShowProductId(orderWork.getShowProductId());
        query.setConcatPhone(orderDetail.getTelephone());
        query.setReceiveTime(receiveTimeSpan);
        query.setWorkResultStatusList(Lists.newArrayList(OrderStatusConsts.WORK_RESULT_FAIL, OrderStatusConsts.WORK_RESULT_DISCARD));
        Integer count = orderWorkListBService.countOrderWorkByQuery(query);
        logger.info("工程师恶意加单奖励工单查询：条件：{}， 结果：{}", JSON.toJSONString(query), count);

        boolean countJug = orderWork.getResultStatus().equals(OrderStatusConsts.WORK_RESULT_FAIL) || orderWork.getResultStatus().equals(OrderStatusConsts.WORK_RESULT_DISCARD);

        if (countJug) {
            return (count < 2) && canBonus;
        } else {
            return (count < 1) && canBonus;
        }
    }


    /**
     * 查询服务商算账结果
     */
    @RequestMapping(value = "/account/result")
    @ResponseBody
    public ResultDTO queryAccountResult(Long orderId, Long workId) {
        return ResultDTO.fail("目前接口不支持获取算账结果");
//        try {
//
//            ResultDTO<OrderDrawingInforDRO> res = zsNormalFinanceWorkBService.getYeyxOrderDrawningInfo(orderId, workId);
//            if (!res.isStatusBool()) {
//                return ResultDTO.fail(res.getMessage());
//            }
//
//            OrderDrawingInforDRO accountDRO = res.getData();
//
//            if (accountDRO == null) {
//                return ResultDTO.success(new ZsAccountResultVO(), GlobalConsts.SUCCESS_MSG);
//            }
//
//            ZsAccountResultVO settleRepVO = BeanMapper.map(accountDRO, ZsAccountResultVO.class);
//
//            //计算提成金额
//            if (settleRepVO != null) {
//                //计算提成金额
//                Integer commissionAmount = Optional.ofNullable(settleRepVO.getServiceProviderRetention()).orElse(0)
//                        - Optional.ofNullable(settleRepVO.getInsurance()).orElse(0)
//                        - Optional.ofNullable(settleRepVO.getHelpEach()).orElse(0)
//                        - Optional.ofNullable(settleRepVO.getDeposit()).orElse(0)
//                        - Optional.ofNullable(settleRepVO.getVoucherShare()).orElse(0)
//                        - Optional.ofNullable(settleRepVO.getDiscountShare()).orElse(0)
//                        - Optional.ofNullable(settleRepVO.getIntegralShare()).orElse(0);
//                settleRepVO.setCommissionAmount(commissionAmount);
//            }
//            return ResultDTO.success(settleRepVO);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultDTO.fail(e.getMessage());
//        }
    }

}
